package com.tywj.buscustomerapp.view.activity;

import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.CityBean;
import com.tywj.buscustomerapp.utils.RecyclerItemClickListener;
import com.tywj.buscustomerapp.utils.SPUtils;
import com.tywj.buscustomerapp.utils.myadapter.CommonRcvAdapter;
import com.tywj.buscustomerapp.utils.myadapter.item.AdapterItem;
import com.tywj.buscustomerapp.view.item.POIItem;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class ChooseLocationActivity extends BaseActivity {
    @BindView(R.id.head_left)
    ImageView back;
    @BindView(R.id.head_title)
    TextView title;
    @BindView(R.id.choose_clear)
    ImageView clear;
    @BindView(R.id.choose_edit)
    EditText editText;
    @BindView(R.id.poi_recycler)
    RecyclerView recyclerView;
    @BindView(R.id.choose_city)
    TextView chooseCity;
    @BindView(R.id.map)
    MapView mMapView;
    @BindView(R.id.hind)
    ImageView hind;
    @BindView(R.id.chooseLo)
    TextView chooseLo;

    private CommonRcvAdapter<PoiItem> adapter;
    private List<PoiItem> pois = new ArrayList<>();
    private int type;
    private CityBean city;
    private AMap map;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    private PoiItem local;


    @Override
    protected int getContentId() {
        return R.layout.activity_choose_location;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        mMapView.onCreate(savedInstanceState);
        if (getIntent()==null){
            finish();
        }
        type = getIntent().getIntExtra("type",0);
        if (type==0){
            title.setText(R.string.nav_title1);
        }else if (type==1){
            title.setText(R.string.nav_title2);
        }else if (type==2){
            title.setText(R.string.nav_title3);
        }else if (type==3){
            title.setText(R.string.nav_title4);
        }
        city=SPUtils.getCity(getApplicationContext());
        if (city!=null && city.getCityId()!=null && !city.getCityId().equals("")){
            chooseCity.setText(city.getCityName());
        }

        adapter = new CommonRcvAdapter<PoiItem>(pois) {
            @NonNull
            @Override
            public AdapterItem createItem(Object type) {
                return new POIItem();
            }
        };
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

    @Override
    protected void initData() {
        super.initData();
        map = mMapView.getMap();
        if (map.getUiSettings()!=null) {
            map.getUiSettings().setZoomControlsEnabled(false);
        }
        copyFile();
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_my_lo);
        myLocationStyle.myLocationIcon(descriptor);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、蓝点不会移动到地图中心点，定位点依照设备方向旋转，并且蓝点会跟随设备移动。
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.transparent));
        myLocationStyle.strokeColor(getResources().getColor(R.color.transparent));
        myLocationStyle.interval(5000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        map.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        map.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        startGetLocation();
        map.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                LatLonPoint latLonPoint = new LatLonPoint(cameraPosition.target.latitude,cameraPosition.target.longitude);
                RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP);
                GeocodeSearch geocoderSearch = new GeocodeSearch(ChooseLocationActivity.this);
                geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                    @Override
                    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                        local = regeocodeResult.getRegeocodeAddress().getPois().get(0);
                        chooseLo.setText("选择("+local.getTitle()+")为"+title.getText());
                    }

                    @Override
                    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {
                    }
                });
                geocoderSearch.getFromLocationAsyn(query);

            }
        });
    }

    public void startGetLocation(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setLocationCacheEnable(false);//关闭定位缓存
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            LatLng latLng = new LatLng(aMapLocation.getLatitude(),aMapLocation.getLongitude());
            CameraUpdate up = CameraUpdateFactory.changeLatLng(latLng);
            up.getCameraUpdateFactoryDelegate().zoom =18;
            map.animateCamera(up);
        }
    };

    private void copyFile(){
        try {
            // 先获取系统默认的文档存放根目录
            File parent_path = Environment.getExternalStorageDirectory();
            File dir = new File(parent_path.getAbsoluteFile(), "com.tywj.buscustomerapp");
            if(!dir.exists()){
                dir.mkdir();
            }
            File file = new File(dir.getAbsoluteFile(), "style.data");
            if(file.exists()){
                map.setCustomMapStylePath(dir.getAbsolutePath()+"/style.data");
                map.setMapCustomEnable(true);
                return;
            }
            //读取数据文件getResources().openRawResource(R.raw.qq);
            InputStream open = this.getResources().openRawResource(R.raw.style);
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            int len;
            byte[] buf = new byte[1024];
            while((len=open.read(buf))!=-1){
                fos.write(buf,0,len);
            }
            map.setCustomMapStylePath(file.getAbsolutePath());
            map.setMapCustomEnable(true);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText("");
            }
        });
        /**
         * 设置recyclerview的点击监听
         */
        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent mIntent = new Intent();
                mIntent.putExtra("poi", pois.get(position));
                setResult(1001,mIntent);
                finish();
            }

            @Override
            public void onItemLongClick(View view, int position) {
            }
        }));
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String search_String = editText.getText().toString();
                if (search_String.length()>0){
                    searchPOI(search_String,city.getCityName());
                }
            }
        });
        chooseCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ChooseLocationActivity.this,ChooseCityActivity.class);
                startActivityForResult(intent,1);
            }
        });

        hind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hind.setVisibility(View.GONE);
                recyclerView.setVisibility(View.GONE);
                editText.setText("");
            }
        });
        chooseLo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (local!=null && !local.getTitle().equals("")){
                    Intent mIntent = new Intent();
                    mIntent.putExtra("poi", local);
                    setResult(1001,mIntent);
                    finish();
                }else{
                    ToastJoe.getmToastJoe().ToastLongShow(ChooseLocationActivity.this,null,"请移动地图选择地点");
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==1002){
            CityBean city = (CityBean) data.getSerializableExtra("city");
            if (city!=null && !city.equals("")){
                this.city = city;
                chooseCity.setText(city.getCityName());
                SPUtils.rememberCity(getApplicationContext(),city);
                if (editText.getText().toString().length()>0){
                    searchPOI(editText.getText().toString(),city.getCityName());
                }

            }
        }
    }


    /**
     * 获取搜索到的数据
     * @param key
     * @param city
     */
    private void searchPOI(String key,String city){
        PoiSearch.Query query = new PoiSearch.Query(key, "", city);
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);//设置查询页码
        PoiSearch poiSearch = new PoiSearch(getApplicationContext(), query);
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if (poiResult!=null && poiResult.getPois()!=null && poiResult.getPois().size()>0){
                    pois.clear();
                    pois = poiResult.getPois();
                    if (pois.size()>0){
                        hind.setVisibility(View.VISIBLE);
                        recyclerView.setVisibility(View.VISIBLE);
                        adapter.setData(pois);
                        adapter.notifyDataSetChanged();
                    }

                }
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {

            }
        });
        poiSearch.searchPOIAsyn();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
        MobclickAgent.onPageStart("位置搜索");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
        MobclickAgent.onPageEnd("位置搜索");
        MobclickAgent.onPause(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mMapView!=null)
            mMapView.onDestroy();
    }
}
